
#include <stdint.h>
#include <string.h>

#include "BSP.h"
//PICC
#include "CardPort.h"
#include "CardPrivate.h"
#include "ISO14443p3a.h"
//ICC

#include "Slot.h"
#include "CardControl.h"

#include "Debug.h"

extern slot_t Slot[1];

static int Card_PICC_Detect(void){
	int ret;
	Port_Picc_SetRf(1);
	BSP_Sleep_Ms(7);
	ret = Port_Picc_Detect(Card_T_CpuA);
	if(!ret){
		Port_Picc_SetRf(0);
	}
	return ret;
}

static int Card_PICC_PowerOn(uint8_t* atr, uint16_t* alen){
	int ret;
	
	Port_Picc_SetRf(0);
	BSP_Sleep_Ms(10);
	Port_Picc_SetRf(1);
	BSP_Sleep_Ms(10);
	
	//activate card
	
	ISO14443AInfo_T a;
	ret = Port_Picc_Activate(Card_T_CpuA, PICC_Op_Activate, &a);
	if(ret){
		DBG_PRINT("Port_Picc_Activate fail:%d\r\n", ret);
		return ret;
	}	
	uint8_t ats[16];
	ret = Port_Picc_Setup(Card_T_CpuA, &a, ats);
	if(ret){
		DBG_PRINT("Port_Picc_Setup fail:%d\r\n", ret);
		return ret;
	}
	uint8_t i = 0;
	//ÀàÐÍ£ºA
	atr[i++] = 1;
	memcpy(&atr[i], a.atqa, sizeof(a.atqa));
	i += sizeof(a.atqa);
	atr[i++] = a.sak;
	atr[i++] = a.ulen;
	memcpy(&atr[i], a.uid, a.ulen);
	i += a.ulen;
	memcpy(&atr[i], ats, ats[0]);
	i += ats[0];
	*alen = i;
	return ret;
}

static int Card_PICC_PowerOff(void){	
	Port_Picc_Deactivate();
	Port_Picc_Destroy();
	Port_Picc_SetRf(0);
	return 0;
}


static int Card_ICC_PowerOn(uint8_t* atr, uint16_t* alen){
	uint8_t buf[32];
	uint8_t len = 0;
	int ret;
	
	CharacterModule_Init();
	Slot_Init();
	ret = Slot_PowerOn(Slot, buf, &len);
	if(ret == 0){
		*alen = len;
	}
	return ret;
}

static int Card_ICC_PowerOff(void){
	return Slot_PowerOff(Slot);
}


int Card_Detect(uint8_t slot){
	int ret;
	if(slot == 0){
		ret = Card_PICC_Detect();
	}
	else{
		ret = 0;
	}
	return ret;
}

int Card_PowerOn(uint8_t slot, uint8_t* atr, uint16_t* alen){
	int ret;
	
	if(slot == 0){
		ret = Card_PICC_PowerOn(atr, alen);
	}
	else{
		ret = Card_ICC_PowerOn(atr, alen);
	}
	return ret;
}


int Card_PowerOff(uint8_t slot){
	int ret;
	if(slot == 0){
		ret = Card_PICC_PowerOff();
	}
	else{
		ret = Card_ICC_PowerOff();
	}
	return ret;
}





